import pyaudio
import numpy as np

def count_hits(audio_data):
    max_value = np.max(audio_data)  # 音频数据的最大值
    min_value = np.min(audio_data)  # 音频数据的最小值
    
    # 计算每个样本点的比例值
    scaled_data = (audio_data - min_value) / (max_value - min_value)
    
    # 计算平均比例值
    mean_value = np.mean(scaled_data)
    
    # 统计明显超出平均值的数量
    hits = np.sum(scaled_data > mean_value + 0.1)  # 超出平均值0.1的数量
    
    # 打印每个样本点的绝对数值
    for i, sample in enumerate(audio_data):
        print(f"样本点 {i+1}，绝对值：{sample}")
    
    return hits

def record_audio(fs, duration):
    audio = pyaudio.PyAudio()

    # 打开音频输入流
    stream = audio.open(format=pyaudio.paInt16,
                        channels=1,
                        rate=fs,
                        input=True,
                        frames_per_buffer=1024)

    frames = []
    for i in range(int(fs / 1024 * duration)):
        # 读取音频数据
        data = stream.read(1024)
        frames.append(data)

    # 关闭流和音频
    stream.stop_stream()
    stream.close()
    audio.terminate()

    # 将帧数据合并为一个连续的数组
    audio_data = np.frombuffer(b"".join(frames), dtype=np.int16)
    return audio_data

fs = 44100  # 采样率
duration = 1  # 录制时长（秒）

print("1秒钟内敲击计数开始...")

# 录制音频数据
audio_data = record_audio(fs, duration)

# 计算击键次数
hits = count_hits(audio_data)

print(f"\n敲击次数: {hits}")
